package com.superhelper.printer.server.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.superhelper.printer.server.PrinterInfo;
import com.superhelper.printer.util.WriterUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

@Component
public class PingEventProcessor {
    @Autowired
    private PrinterInfo printerInfo;

    // 0X00 代表状态正常、0X04 代表打 印机缺纸、0X80 代表打印机过热)
    // printerStatus: 0 正常，4 缺纸， 128 打印机过热
    public void process(int printerId, int printerStatus, ChannelHandlerContext ctx) {
        System.out.println(printerId + "状态：" + printerStatus);
        ctx.channel().writeAndFlush(buildMsg());
        printerInfo.renew(printerId, printerStatus, ctx.channel());
    }

    private ByteBuf buildMsg() {
        ByteBuf buf = Unpooled.buffer(128);
        buf.writeByte(Integer.parseInt("1E", 16));
        int byteNum = 8;// 8是固定的长度
        // 字节长度
        buf.writeShort(byteNum);
        // Mod1
        buf.writeByte(2);
        // Mod2
        buf.writeByte(0);
        // FLAG
        buf.writeByte(-1);// Integer.parseInt("FF", 16)

        // CMD
        buf.writeByte(Integer.parseInt("51", 16));

        int sum = WriterUtils.checkSum(buf.copy());
        System.out.println("sum = " + sum);
        // chsum
        buf.writeByte(sum);
        return buf;
    }
}
